package main

import (
	"bolt-manager/controller"
	"bolt-manager/middleware"
	"bolt-manager/model"
	"bolt-manager/util"
	"embed"
	"flag"
	log "github.com/sirupsen/logrus"
	"io/fs"
	"net/http"
)

//go:embed web
var web embed.FS

func main() {
	// 解析命令行参数
	flag.StringVar(&model.Port, "p", "9815", "监听端口")
	flag.StringVar(&model.DbPath, "db", "./", "数据库文件夹路径")
	flag.Parse()

	// 初始化日志
	middleware.InitLog()

	// API接口路由
	http.HandleFunc("/api/queryDataBaseList", middleware.GlobalRecover(controller.QueryDataBaseList))
	http.HandleFunc("/api/queryBucketTree", middleware.GlobalRecover(controller.QueryBucketTree))
	http.HandleFunc("/api/queryBucketKeys", middleware.GlobalRecover(controller.QueryBucketKeys))
	http.HandleFunc("/api/queryKeyValue", middleware.GlobalRecover(controller.QueryKeyValue))
	http.HandleFunc("/api/addBucket", middleware.GlobalRecover(controller.AddBucket))
	http.HandleFunc("/api/deleteBucket", middleware.GlobalRecover(controller.DeleteBucket))
	http.HandleFunc("/api/addBucketKey", middleware.GlobalRecover(controller.AddBucketKey))
	http.HandleFunc("/api/updateBucketKey", middleware.GlobalRecover(controller.UpdateBucketKey))
	http.HandleFunc("/api/deleteBucketKey", middleware.GlobalRecover(controller.DeleteBucketKey))

	// 静态资源路由
	webFs, err := fs.Sub(web, "web")
	if err == nil {
		http.Handle("/", http.FileServer(http.FS(webFs)))
	}

	// 启动浏览器
	if err := util.ChromeApp("http://127.0.0.1:"+model.Port, "", -1, -1, "--start-maximized"); err != nil {
		log.Warn(err)
	}

	// 启动服务
	log.Info("启动服务，端口：" + model.Port + "，数据库目录：" + model.DbPath)
	log.Error(http.ListenAndServe(":"+model.Port, nil))
}
